package com.sunchangpeng.wechat.mp.media;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.sunchangpeng.wechat.core.WechatClient;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.media.bean.MediaType;
import com.sunchangpeng.wechat.mp.media.bean.MpArticle;
import com.sunchangpeng.wechat.mp.media.bean.MpNewsPage;
import lombok.Data;

import java.util.List;

import static com.sunchangpeng.wechat.core.utils.StringPool.MEDIA_NAME;

public class Mpnews {
    protected WechatClient wechatClient;

    public void setWechatClient(WechatClient wechatClient) {
        this.wechatClient = wechatClient;
    }

    /**
     * 上传图文消息内的图片获取URL
     */
    public String uploadMpNewsImage(String fileName, byte[] content) {
        String url = EndpointProvider.get("url.mpnews.image.upload");
        String response = wechatClient.multiForm(url, MEDIA_NAME, fileName, content);
        return JSON.parseObject(response).getString("url");
    }

    /**
     * 新增永久图文素材
     */
    public String addMpNews(List<MpArticle> articles) {
        String url = EndpointProvider.get("url.material.mpnews.add");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject().fluentPut("articles", articles)));
        return JSON.parseObject(response).getString("media_id");
    }


    /**
     * 修改图文素材
     */
    public void updateMpNews(String mediaId, int index, MpArticle article) {
        String url = EndpointProvider.get("url.material.mpnews.update");
        wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject()
                .fluentPut("media_id", mediaId)
                .fluentPut("index", index)
                .fluentPut("articles", article)));
    }

    /**
     * 获取图文素材
     */
    public List<MpArticle> getMpNews(String mediaId) {
        String url = EndpointProvider.get("url.material.mpnews.get");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject().fluentPut("media_id", mediaId)));
        return JSON.parseObject(response, MpArticleWrapper.class).getList();
    }

    /**
     * 获取图文素材列表
     */
    public MpNewsPage listMpNews(int offset, int count) {
        String url = EndpointProvider.get("url.material.list");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject()
                .fluentPut("type", MediaType.news.name())
                .fluentPut("offset", offset)
                .fluentPut("count", count)));
        return JSON.parseObject(response, MpNewsPage.class);
    }

    @Data
    static class MpArticleWrapper {
        @JSONField(name = "news_item")
        private List<MpArticle> list;

        @JSONField(name = "create_time")
        private long createTime;

        @JSONField(name = "update_time")
        private long updateTime;
    }
}
